package com.ys.peony.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.ys.peony.R;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.BaseActivity;
import com.ys.peony.utils.LogUtil;
import com.ys.peony.utils.SharePreferencesUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;

/**
 * 更换头像
 */
public class ClipHeadPhotoActivity extends BaseActivity implements View.OnClickListener {
    //拍照
    @BindView(R.id.cliphead_photo_btn)
    Button btnTakephoto;

    //相册
    @BindView(R.id.cliphead_album_btn)
    Button btnPhotos;

    @BindView(R.id.cliphead_cancle_btn)
    Button btnCancle;

    @BindView(R.id.cliphead_ll)
    LinearLayout linearLayout;

    // 头像Bitmap
    Bitmap head;
    //sd路径
    private static String path = YSConstant.SD_FILE_PATH;
    private String imageName = SharePreferencesUtils.getInstance().getUserId();
    private Uri imageUrl;

    @Override
    protected int getContentResId() {
        return R.layout.clipheadphoto_activity_layout;
    }

    @Override
    protected void initView() {
        //初始化控件
        linearLayout.setOnClickListener(this);
        btnPhotos.setOnClickListener(this);
        btnTakephoto.setOnClickListener(this);
        btnCancle.setOnClickListener(this);
    }

    public boolean onTouchEvent(MotionEvent event) {
        finish();
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //从相册里面取照片
            case R.id.cliphead_album_btn:
                Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent1, 1);
                break;
            //调用相机拍照
            case R.id.cliphead_photo_btn:
                Intent intent2 = new Intent("android.media.action.IMAGE_CAPTURE");
                File takephotoimage = new File(path, imageName);
                try {
                    takephotoimage.delete();
                    takephotoimage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                imageUrl = Uri.fromFile(takephotoimage);
                intent2.putExtra(MediaStore.EXTRA_OUTPUT, imageUrl);
                startActivityForResult(intent2, 2);
                break;
            case R.id.cliphead_cancle_btn:
                finish();
            default:
                break;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    //裁剪图片
                    cropPhoto(data.getData());
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
//                    File temp = new File(path +"/"+ imageName);
                    //裁剪图片
                    LogUtil.i("aaaa", "---URI------" + imageUrl + "---------");
                    cropPhoto(imageUrl);
                }

                break;
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        //保存在SD卡中
                        setPicToView(head);
                        //TODO 上传服务器
                        uploadImage();
                    }
                }
                finish();
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 调用系统的裁剪
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
            // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        // 创建文件夹
        file.mkdirs();
        //图片名字
        String fileName = path + "/" + imageName;
        try {
            // 把数据写入文件
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
//            SharePreferencesUtils.getInstance().setKeyValue(Constants.SP_HEAD_ICON,fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private void uploadImage() {
       //TODO 上传头像
        String fileName = path + "/" + imageName;
        Intent it=new Intent();
        it.putExtra("headImgPath",fileName);
        setResult(RESULT_OK,it);
        finish();
    }
}
